package com.framework.core.sqlfactory.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.framework.core.utils.PropertiesUtils;

//jdbc连接，模拟数据库连接池
public class BaseJdbcConnection {

	private static Connection connection;

	// 数据源配置固定字段
	private final static String urlString = "datasource.url";
	private final static String usernameString = "datasource.username";
	private final static String passwordString = "datasource.password";
	private final static String driverClassNameString = "datasource.driverClassName";

	private static String url;
	private static String username;
	private static String password;
	private static String driverClassName;

	// 模拟数据库连接池
	private static List<Connection> list = new ArrayList<Connection>();

	// 初始化
	static {

		url = PropertiesUtils.getPropertiesValueByName(urlString);
		username = PropertiesUtils.getPropertiesValueByName(usernameString);
		password = PropertiesUtils.getPropertiesValueByName(passwordString);
		driverClassName = PropertiesUtils.getPropertiesValueByName(driverClassNameString);

		for (int i = 0; i < 5; i++) {
			connection = getJdbcConnection();
			list.add(connection);
		}
	}

	// 请求数据库连接
	private synchronized static Connection getJdbcConnection() {

		try {
			Class.forName(driverClassName);
			connection = DriverManager.getConnection(url, username, password);
			return connection;
		} catch (ClassNotFoundException | SQLException e) {
			System.out.println("请求数据库连接异常！");
			e.printStackTrace();
		}
		return null;
	}

	// 获取连接
	public static Connection getConnection() {

		if (list.size() > 0) {
			return list.remove(0);
		} else if (list.size() == 1) {
			for (int i = 0; i < 4; i++) {
				connection = getJdbcConnection();
				list.add(connection);
			}
		}
		return null;
	}

}
